<template>
  <el-dialog
    top="80px"
    :visible.sync="isVisible"
    :title="title"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <el-container>
      <el-main
        v-loading="submitLoading"
        :style="{ 'max-height': maxHeightDialog }"
        :element-loading-text="submitLoading ? '提交中...' : '加载中...'"
        class="container-main"
      >
        <div>
          <div class="title">
            <span>填写信息</span>
          </div>

          <el-card class="card" shadow="never" style="background: #fafafa">
            <div style="margin-left: -12px; margin-right: -12px">
              <el-row>
                <el-col :span="23">
                  <el-form
                    ref="elForm"
                    size="small"
                    label-position="right"
                    :model="form"
                    :rules="rules"
                    label-width="120px"
                  >
                    <el-row>
                      <el-col :span="24">
                        <el-form-item label="上传人脸图片" prop="facePic">
                          <el-upload
                            :action="uploadUrl"
                            :headers="{ Authorization: token }"
                            list-type="picture-card"
                            :show-file-list="false"
                            :on-success="handleSuccess"
                            :on-error="handleImgError"
                            :disabled="facePicUrl != ''"
                          >
                            <img
                              v-if="facePicUrl != ''"
                              :src="facePicUrl"
                              style="
                                width: 146px;
                                height: 146px;
                                display: block;
                              "
                              @click="handlePreview"
                            />

                            <div
                              style="
                                background-color: rgba(0, 0, 0, 0.45);
                                width: 16px;
                                height: 16px;
                                position: absolute;
                                top: 2px;
                                left: 130px;
                              "
                              v-if="facePicUrl != ''"
                            >
                              <el-popconfirm
                                title="确定要删除该人脸图吗？"
                                @confirm="onConfirmDelete"
                              >
                                <i
                                  class="el-icon-close"
                                  style="
                                    position: absolute;
                                    top: 2px;
                                    right: 0px;
                                    font-size: 14px;
                                    color: white;
                                  "
                                  slot="reference"
                                ></i>
                              </el-popconfirm>
                            </div>
                            <i
                              v-if="facePicUrl == ''"
                              class="el-icon-plus avatar-uploader-icon"
                            ></i>
                          </el-upload>
                        </el-form-item>
                      </el-col>
                    </el-row>

                    <el-row>
                      <el-col :span="24">
                        <el-form-item label="姓名" prop="name">
                          <el-input
                            v-model="form.name"
                            placeholder="请输入姓名"
                            clearable
                          />
                        </el-form-item>
                      </el-col>
                    </el-row>

                    <el-row>
                      <el-col :span="24">
                        <el-form-item label="身份证号" prop="sfzh">
                          <el-input
                            v-model="form.sfzh"
                            placeholder="请输入身份证号"
                            clearable
                          />
                        </el-form-item>
                      </el-col>
                    </el-row>

                    <el-row>
                      <el-col :span="24">
                        <el-form-item label="性别" prop="xbdm">
                          <el-select
                            v-model="form.xbdm"
                            placeholder="请选择性别"
                            filterable
                            clearable
                            style="width: 100%"
                          >
                            <el-option
                              v-for="item of xbdmList"
                              :key="item.value"
                              :label="item.label"
                              :value="item.value"
                            /> </el-select
                        ></el-form-item>
                      </el-col>
                    </el-row>

                    <el-row>
                      <el-col :span="24">
                        <el-form-item label="标签" prop="label">
                          <el-input
                            v-model="form.label"
                            placeholder="请输入标签"
                            clearable
                          />
                        </el-form-item>
                      </el-col>
                    </el-row>

                    <el-row>
                      <el-col :span="24">
                        <el-form-item label="备注" prop="remark">
                          <el-input
                            v-model="form.remark"
                            placeholder="请输入备注"
                            clearable
                          />
                        </el-form-item>
                      </el-col>
                    </el-row>
                  </el-form>
                </el-col>
              </el-row>
            </div>
          </el-card>
        </div>
      </el-main>

      <el-footer>
        <el-button
          size="medium"
          icon="el-icon-close"
          :disabled="submitLoading"
          style="width: 120px; margin-right: 10px"
          @click="isVisible = false"
        >
          取消
        </el-button>
        <el-button
          size="medium"
          type="primary"
          icon="el-icon-check"
          :disabled="submitLoading"
          :loading="submitLoading"
          style="width: 120px"
          @click="toSubmit"
        >
          {{ params.type == 'edit' ? '修改' : '提交' }}
        </el-button>
      </el-footer>
    </el-container>

    <el-dialog
      :visible.sync="imgDialogVisible"
      :title="'人脸图片'"
      top="100px"
      width="500px"
      :append-to-body="true"
    >
      <img :src="facePicUrl" alt="" style="padding: 20px; width: 100%" />
    </el-dialog>
  </el-dialog>
</template>

<script>
import dataFormMixins from '@/mixins/data-form-mixins'
import EpidemicPreventionManageApi from '@/api/epidemic-prevention-manage'
import { getToken } from '@/utils/auth'

export default {
  name: 'PersonnelRecordsAdd',
  components: {},
  mixins: [dataFormMixins],
  props: {
    dialogVisible: {
      type: Boolean,
      default: false,
    },
    title: {
      type: String,
      default: '',
    },
    params: {
      type: Object,
      default: () => {
        return {}
      },
    },
  },
  data() {
    return {
      xbdmList: [
        {
          label: '未知的性别',
          value: '0',
        },
        {
          label: '男性',
          value: '1',
        },
        {
          label: '女性',
          value: '2',
        },
        {
          label: '未说明的性别',
          value: '9',
        },
      ],

      uploadUrl:
        process.env.VUE_APP_BASE_API +
        'system/files/uploadFolder?FolderName=GridFile',
      token: 'bearer ' + getToken(),
      facePicUrl: '',
      imgDialogVisible: false,
    }
  },
  computed: {
    isVisible: {
      get() {
        return this.dialogVisible
      },
      set() {
        this.toClose()
      },
    },
  },
  mounted() {
    this.form = this.initForm()
    this.rules = this.initRules()
    if (this.params.type === 'edit') {
      Object.keys(this.form).forEach((key) => {
        Object.keys(this.params.item).forEach((_key) => {
          if (key == _key) {
            this.form[key] = this.params.item[_key]
          }
        })
      })
      this.facePicUrl = this.form.facePic ? this.form.facePic : ''
    }
  },
  methods: {
    initForm() {
      return {
        id: '',
        tenantId: '', // 租户ID
        facePic: '', // 人脸图片
        facePicId: null, // 人脸图片
        name: '', // 姓名
        sfzh: '', // 身份证号
        xbdm: '', // 性别
        label: '', // 标签
        remark: '', // 备注
      }
    },
    initRules() {
      return {
        facePic: this.getValidatorForm(),
        name: this.getValidatorForm(),
        sfzh: this.getValidatorForm(),
        xbdm: this.getValidatorForm('change'),
        label: this.getValidatorForm(),
        remark: this.getValidatorForm(),
      }
    },

    handleSuccess(response, file, fileList) {
      // console.log('response=', response)
      // console.log('file=', file)
      // console.log('fileList=', fileList)
      this.facePicUrl = URL.createObjectURL(file.raw)
      this.form.facePic = response.url
      this.form.facePicId = response.uid
      this.$message.success(`人脸图片上传成功！`)
      // console.log('form>>', this.form)
    },
    handleImgError() {
      this.$message.error(`人脸图片上传失败`)
    },
    onConfirmDelete() {
      this.facePicUrl = ''
      this.form.facePic = ''
    },
    handlePreview() {
      this.imgDialogVisible = true
    },

    toClose() {
      this.$emit('close')
    },
    toSubmit() {
      this.$refs.elForm.validate((valid) => {
        console.log('form', this.form)
        if (valid) {
          const model = this.formatFormData(this.form)
          console.log('model=', model)
          this.submitLoading = true
          if (this.params.type === 'add') {
            EpidemicPreventionManageApi.addPerson(model)
              .then((res) => {
                if (res.data.code == 200) {
                  this.$message({
                    message: '提交成功！',
                    type: 'success',
                  })
                  this.submitLoading = false
                  this.isVisible = false
                  this.$emit('submit', 'add')
                } else {
                  this.$message({
                    message: '提交失败！',
                    type: 'error',
                  })
                  this.submitLoading = false
                }
              })
              .catch(() => {
                this.submitLoading = false
              })
          } else {
            EpidemicPreventionManageApi.updatePerson(model)
              .then((res) => {
                if (res.data.code == 200) {
                  this.$message({
                    message: '修改成功！',
                    type: 'success',
                  })
                  this.submitLoading = false
                  this.isVisible = false
                  this.$emit('submit', 'edit')
                } else {
                  this.$message({
                    message: '修改失败！',
                    type: 'error',
                  })
                  this.submitLoading = false
                }
              })
              .catch(() => {
                this.submitLoading = false
              })
          }
        } else {
          this.$message({
            message: '*必填项不能为空！',
            type: 'warning',
            duration: 4000,
          })
          return false
        }
      })
    },
  },
}
</script>

<style scoped lang="scss">
@import '../../../../../styles/part-custom';
</style>
